package Stages

import Actors.Mario
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.ui.Touchpad
import drawable
import floatHeight
import floatWidth
import setOnTouchListener

/**
 * 游戏舞台
 */
class GameStage(textureAtlas: TextureAtlas) : Stage()
{

    // 马里奥对象
    private val mario by lazy { Mario(0f, Gdx.graphics.floatHeight / 2, textureAtlas) }

    private val touchPad by lazy {
        val touchPadStyle = Touchpad.TouchpadStyle(drawable("touch_pad_bg.png")
                , drawable("touch_pad_knob.png"))
        Touchpad(1f, touchPadStyle).apply {
            setBounds(0f, 0f, 100f, 100f)
        }
    }

    init
    {
        this.addActor(mario)
        this.addActor(touchPad)
    }

    private var lastState: Mario.STATE? = null
    override fun draw()
    {
        val x = touchPad.knobPercentX * 1f
        val y = touchPad.knobPercentY * 1f

        when
        {
            x > 0 ->
            {
                mario.state = Mario.STATE.RIGHT
            }
            x < 0 ->
            {
                mario.state = Mario.STATE.LEFT
            }
            x == 0f ->
            {
                if (Mario.STATE.RIGHT == lastState)
                {
                    mario.state = Mario.STATE.RIGHT_IDLE
                } else if (Mario.STATE.LEFT == lastState)
                {
                    mario.state = Mario.STATE.LEFT_IDLE
                }
            }
        }
        lastState = mario.state
        mario.x += x
        mario.y += y

        if (mario.x <= 0)
        {
            mario.x = 0f
        }
        if (mario.x >= (Gdx.graphics.floatWidth - mario.width))
        {
            mario.x = (Gdx.graphics.floatWidth - mario.width)
        }

        if (mario.y <= 0)
        {
            mario.y = 0f
        }

        if (mario.y >= (Gdx.graphics.floatHeight - mario.height))
        {
            mario.y = Gdx.graphics.floatHeight - mario.height
        }
        
        
        super.draw()
    }
}